package com.java.androidmarket.controller;

import com.java.androidmarket.dto.CommentDTO;
import com.java.androidmarket.entity.Comment;
import com.java.androidmarket.entity.Order;
import com.java.androidmarket.entity.Result;
import com.java.androidmarket.service.CommentService;
import com.java.androidmarket.service.OrderService;
import com.java.androidmarket.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * description:
 * author:张腾
 * date:2021-04-24
 */

@RestController
@CrossOrigin
@RequestMapping("comment")
@Api(tags = "评论模块")
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("getComment")
    @ApiOperation(value = "获取评论", notes = "根据商品id获取每个商品的评论信息")
    @ApiImplicitParam(dataType = "int", name = "goodsId", value = "商品ID")
    public Result getComment(int goodsId){
        List<Comment> comments = null;

        if (redisUtils.exists("Comment:"+goodsId)) {
            System.out.println("redis查找评论");
            comments = (List<Comment>) redisUtils.hmGet("Comment:"+goodsId, "comments");
        }else{
            System.out.println("数据库查找评论");
            comments = commentService.getComment(goodsId);
            if (comments.size()<=0){
                return Result.success("空空如也",0);
            }else{
                redisUtils.hmSet("Comment:"+goodsId,"comments",comments);
                redisUtils.hmSet("Comment:"+goodsId,"total",comments.size());
            }
        }

        return Result.success(comments, comments.size());

    }


    @PostMapping("addComment")
    @ApiOperation(value = "添加评论", notes = "添加一条评论记录")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Comment", name = "comment", value = "comment评论实体类"),
            @ApiImplicitParam(dataType = "String", name = "orderSn", value = "评论所属订单编号")
    })
    @Transactional
    public Result addComment(@RequestBody CommentDTO commentDTO){

        List<Comment> commentList = commentDTO.getCommentList();
        String orderSn = commentDTO.getOrderSn();

        for (Comment comment : commentList) {
            if (redisUtils.exists("Comment:"+comment.getGoodsId())) {
                redisUtils.del("Comment:"+comment.getGoodsId());
            }

            commentService.addComment(comment);
        }
        Order order = new Order();
        order.setOrderSn(orderSn).setOrderStatus(2);
        orderService.changeStatus(order);

        orderService.deleteRedis(orderSn);
        return Result.success();
    }

}
